package com.axcbd.demo.service;

import com.axcbd.demo.model.Temperature;
import com.axcbd.demo.repository.HumidityRepository;
import com.axcbd.demo.repository.TemperatureRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;

@Service
public class TemperatureService {

    @Autowired
    private TemperatureRepository temperatureRepository;

    public List<Temperature> getLatestNTemperature(int n) {
        return temperatureRepository.findTopNByCreatedAtDesc(n);
    }

    public void saveTemperature(Temperature temperature) {
        ZonedDateTime beijingTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        Instant instant = beijingTime.toInstant();
        Date date = Date.from(instant);
        temperature.setCreatedAt(date);
        temperatureRepository.save(temperature);
    }
}
